//
//  RegistFirstStepView.m
//  QRMaster
//
//  Created by myApple on 15/3/21.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RegistView.h"
#import "MyRsa.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "LineView.h"
#import "Reachability.h"
#import "validateInputValue.h"

@interface RegistView ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    UIImageView * PromtImgView;
    UITextField * checkTextField;
    UIButton * checkBtn;
    
    UIImageView * newPWDView;
    
    NSTimer * time;
}

@end

static NSInteger count = 0;

@implementation RegistView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
        [time setFireDate:[NSDate distantPast]];
        [self prepareView];
        count=0;
    }
    return self;
}

-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 10;
    float y = 20;
    float width = 120;
    float height = 40;
    
    UILabel * checkLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    checkLabel.text = NSLocalizedString(@"checkNum", nil);
    checkLabel.font = [UIFont systemFontOfSize:14.0];
    checkLabel.textAlignment=NSTextAlignmentCenter;
    [self addSubview:checkLabel];
    
    x += width;
    width = ScreenWidth - x - 20;
    checkTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    checkTextField.placeholder =  NSLocalizedString(@"checkNum", nil);
    checkTextField.font = [UIFont boldSystemFontOfSize:14.0];
    checkTextField.borderStyle = UITextBorderStyleNone;
    checkTextField.keyboardType = UIKeyboardTypeNumberPad;
    checkTextField.delegate = self;
    checkTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:checkTextField];
    LineView * passWordLine = [[LineView alloc]initWithFrame:CGRectMake(20, y+height - 5, ScreenWidth - 40, 1)];
    passWordLine.backgroundColor = RGBA(237, 238, 241, 1);
    [self addSubview:passWordLine];
    
    x = ScreenWidth /2.0 - 100;
    y += height + 10;
    width = 200;
    checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(x, y, width, height);
    [checkBtn setTitle: NSLocalizedString(@"notReceiveCheckNum", nil) forState:0];
    [checkBtn setTitleColor:RGBA(135, 199, 66, 1) forState:0];
    checkBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    checkBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [checkBtn addTarget:self action:@selector(checkClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:checkBtn];
    
    x = 20;
    width = ScreenWidth - 2 * x;
    y += height + 10;
    height = 40;
    UIButton * MakeSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    MakeSureBtn.frame = CGRectMake(x, y, width, height);
    [MakeSureBtn setTitle:NSLocalizedString(@"completeRegist", nil) forState:0];
    [MakeSureBtn setBackgroundColor:RGBA(135, 199, 66, 1)];
    [MakeSureBtn setTitleColor:[UIColor whiteColor] forState:0];
    MakeSureBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [MakeSureBtn addTarget:self action:@selector(MakeSureClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:MakeSureBtn];
    
}

-(void)checkClick:(UIButton *)btn
{
    UIAlertView * alter = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sendAgainOrNot", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil)otherButtonTitles:NSLocalizedString(@"alterSure", nil), nil];
    [alter show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        count=0;
        [self GetData];
    }
}


//启动定时器
-(void)updateTime
{
    count ++;
    if (count >= 60) {
        if ([time isValid]) {
            [time invalidate];
            time = nil;
            count = 0;
        }
        [checkBtn setTitle:NSLocalizedString(@"notReceiveCheckNum", nil) forState:0];
        checkBtn.userInteractionEnabled = YES;
        return;
    }
    else
    {
        checkBtn.userInteractionEnabled = NO;
    }
    [checkBtn setTitle:[NSString stringWithFormat:@"%lu%@",(long)(60 - count),NSLocalizedString(@"timePromtLast", nil)] forState:0];
    [checkBtn setTitleColor:RGBA(135, 199, 66, 1) forState:0];
}

//再次获取验证码
-(void)GetData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    if([validateInputValue isPureNumandCharacters:_mobile]==YES)
    {
         [postDict setValue:_mobile forKey:@"mobile"];
    }
    else if ([validateInputValue validateEmail:_mobile]==YES)
    {
        [postDict setValue:_mobile forKey:@"email"];
    }
    [rnk initWithPath:POST(REGISTERVCODE) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            time = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
            [PromptInfoView showMessage:NSLocalizedString(@"sendAgainSuccess", nil)];
            
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self];
        }

    }];

    
}


//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        return YES;
    }
    return NO;
}



//确定注册
-(void)MakeSureClick:(UIButton *)btn
{
    checkTextField.text = [checkTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (checkTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"vcodeWrong", nil)];
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(LastStepView:registerWay:)]) {
        if ([validateInputValue isPureNumandCharacters:self.mobile] ) {
            [_delegate LastStepView:checkTextField.text registerWay:@"0"];
        }
        else
        {
            [_delegate LastStepView:checkTextField.text registerWay:@"1"];
        }
        
    }
    
}

-(void)hiddenKeyboard
{
    [checkTextField resignFirstResponder];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KCHiddenKeyBoardNotification" object:nil];
}


@end
